package com.example.demo.common.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.NumberFormat;

/**
 * Jackson
 *
 * @author Shanks
 * @date 2020-10-30
 */
public class MoneySerializer extends JsonSerializer<Number> {

    @Override
    public void serialize(Number number, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 获取当前货币格式化实例
        NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
        // 设置数的小数部分所允许的最小位数(如果不足后面补0)
        numberFormat.setMinimumFractionDigits(2);
        // 设置数的小数部分所允许的最大位数(如果超过会四舍五入)
        numberFormat.setMaximumFractionDigits(3);
        jsonGenerator.writeString(numberFormat.format(number));
    }
}